# -*- coding: utf-8 -*-
"""
@Time : 2024/3/1 9:04 PM
@Author: imamhusan
@Des: 描述
"""
from fastapi import APIRouter, Request
from core.Response import success, fail
from models.user import User
from schemes.user import LoginUser
from core.Auth import create_token
import time
from config import settings

router = APIRouter(prefix='/user')


@router.post('/login', description='登录接口')
async def user_login(req: Request, post: LoginUser):
    try:
        user = await User.get_or_none(username=post.username, password=post.password)
        if user:
            session_id = str(int(time.time()))
            data = {
                'user_id': user.pk,
                'user_type': user.user_type,
                'session_id': session_id
            }
            token = create_token(data=data)
            await req.app.state.token_redis.set(name=user.pk, value=session_id, ex=settings.JWT_EXPIRE_TIME)
            return success(data=token, msg='登录成功')
        return success(msg='用户名或密码错误')
    except Exception as e:
        return fail(msg=str(e))


@router.post('/oauth2', description='SwaggerUI测试登录接口')
async def user_login(req: Request):
    try:
        form_data = await req.form()
        username = form_data.get('username')
        password = form_data.get('password')
        user = await User.get_or_none(username=username, password=password)
        if user:
            data = {
                'user_id': user.pk,
                'user_type': user.user_type
            }
            jwt_token = create_token(data=data)
            return {"access_token": jwt_token, "token_type": "bearer"}
        return success(msg='用户名或密码错误')
    except Exception as e:
        return fail(msg=str(e))